package cn.virens.packet.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.virens.TioUtil;
import cn.virens.common.ByteUtil;
import cn.virens.packet.DBPacket;
import cn.virens.packet.WritePacket;

public abstract class AbstractFactory {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 根据 包生成待发送数据帧
	 * 
	 * @param  packet         指令包
	 * @param  channelContext 连接对象
	 * @param  resume         手动指令包
	 * @return
	 */
	public WritePacket build(DBPacket packet, ChannelContext channelContext, boolean resume) {
		try {
			if (StrUtil.equals(packet.mac(), TioUtil.imei(channelContext))) {
				JSONObject json = packet.json();

				WritePacket writePacket = TioUtil.write(channelContext);
				writePacket.data(Assert.notNull(data(json)));
				writePacket.cmd(Assert.notNull(cmd(json)));
				writePacket.model(model(json));
				writePacket.resume(resume);

				return writePacket;
			} else {
				return null;
			}
		} catch (Exception e) {
			logger.error("设备({})构建包失败：{}", TioUtil.name(channelContext), e.getMessage());
		}

		return null;
	}

	/**
	 * 传入HEX_CMD 与对应的数据包进行比较
	 * 
	 * @param  cmd    HEX_CMD
	 * @param  packet 队列数据包
	 * @return
	 */
	public boolean vail(String cmd, DBPacket packet) {
		return cmd != null && cmd.equals(cmd(packet.json()));
	}

	/**
	 * 根据 DATA 属性获取对应的CMD
	 * 
	 * @param  json
	 * @return
	 */
	protected String cmd(JSONObject json) {
		return "";
	}

	/**
	 * 根据 DATA 属性生成对应的byte数组
	 * 
	 * @param  json
	 * @return
	 */
	protected byte[] data(JSONObject json) {
		return ByteUtil.EMPTY_BYTES;
	}

	/**
	 * 根据DATA属性获取对应的控制模式
	 * 
	 * @param  json
	 * @return
	 */
	protected String model(JSONObject json) {
		return null;
	}
}
